package com.example.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author zhangyx
 * @desc
 * @date 2020/8/13 17:28
 **/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {



    //定义用户信息服务(查询用户信息)
   /* @Bean
    public UserDetailsService userDetailsService(){
        //基于内存
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("123").authorities("p2").build());
        return manager;
    }*/

   /* @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("zhangsan").password("123").roles("p1")
                .and()
                .withUser("lisi").password("123").roles("p2");
    }*/

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //安全拦截机制(最重要)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/r/p1").hasAuthority("p1")
                .antMatchers("/r/p2").hasAuthority("p2")
                .antMatchers("/").permitAll() //除了/r/**请求，其他请求都可直接访问
                .anyRequest().authenticated() //所有/r/**的请求都必须通过认证
                .and()
                .formLogin() //允许表单登录
                .loginPage("/login-view")
                .loginProcessingUrl("/login")
                .successForwardUrl("/login-success")
                .permitAll()//自定义表单登录成功地址
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login-view");
    }
}
